package com.pactera.madp.cp.job.sync;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.pactera.madp.admin.api.vo.SysFileVo;
import com.pactera.madp.common.core.exception.CheckedException;
import com.pactera.madp.cp.api.bo.ChannelUniqueQrCodeBO;
import com.pactera.madp.cp.api.dto.channel.channelcodeadddtos.AutoAddFriendMsg;
import com.pactera.madp.cp.api.entity.channel.ChannelCodeEntity;
import com.pactera.madp.cp.common.constant.Constant;
import com.pactera.madp.cp.common.util.FileUtils;
import com.pactera.madp.cp.common.util.WxApiUtils;
import com.pactera.madp.cp.common.util.file.FilesUtil;
import com.pactera.madp.cp.service.IChannelCodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @author: yangpengwei
 * @time: 2021/3/2 10:49 上午
 * @description 渠道码异步任务
 */
@Component
@EnableAsync
@Slf4j
public class WorkChannelCodeSyncLogic {

    @Autowired
    private IChannelCodeService channelCodeService;

    /**
     * 创建微信 配置客户联系「联系我」方式 二维码
     */
    public boolean onCreateWxAddContactWayQrcode(ChannelCodeEntity entity, Map<String, List<?>> map) {
        int corpId = entity.getCorpId();
        boolean skipVerify = false;
        // 是否开启自动添加好友 1-开启 2-关闭
        if (entity.getAutoAddFriendStatus().equals(1)) {
            // 自动通过好友开启时间状态值（1为全天开启  2为选择时间段）
            if (entity.getAutoAddFriendTimeStatus().equals(1)) {
                skipVerify = true;
            } /*else {
                AutoAddFriendMsg msg = JSONObject.parseObject(entity.getAutoAddFriendMsg(), AutoAddFriendMsg.class);
                DateTime now = DateTime.now();
                long time = now.getTime();
                long startTime = DateUtil.parseDateTime(DateUtil.now().split(" ")[0] + " " + msg.getAutoAddFriendStartTime() + ":00").getTime();
                long endTime = DateUtil.parseDateTime(DateUtil.now().split(" ")[0] + " " + msg.getAutoAddFriendEndTime() + ":00").getTime();
                if (time >= startTime && time <= endTime){
                    skipVerify = true;
                }
            }*/
        }

        int type = 0;
        if (map.get("eIds").size() > 1) {
            type = 2;
        } else {
            type = 1;
        }

//         status 组成规则: channelCodeId- + entity.getId
        String state = "channelCodeId-" + entity.getId();
        log.info("state:" + state);
        String resultJson = null;
        if (entity.getCustomerRemarksStatus().equals(1)) {
            resultJson = WxApiUtils.requestCreateContactWayAndRemark(corpId, type, skipVerify, state, map.get("eIds"), map.get("dId"), "-" + entity.getCustomerRemarksMsg());
        } else {
            // 微信获取二维码
            resultJson = WxApiUtils.requestCreateContactWay(corpId, type, skipVerify, state, map.get("eIds"), map.get("dId"));
        }
//
        JSONObject jsonObject = JSON.parseObject(resultJson);
        String qrcodeUrl = jsonObject.getString("qr_code");
        String wxConfigId = jsonObject.getString("config_id");

//         上传图片
        String qrcodeFileName = FileUtils.getFileNameOfContactWayQrCode(entity.getName());
        SysFileVo sysFileVo = FilesUtil.uploadFileByURL(qrcodeUrl, qrcodeFileName, true);

//        DownUploadQueueUtils.uploadFileByUrl(qrcodeFileName, qrcodeUrl);

        if (StrUtil.isBlank(entity.getAvatarUrl())) {
            entity.setQrcodeUrl(sysFileVo.getUrl());
            entity.setWxConfigId(wxConfigId);
        } else {
            ChannelUniqueQrCodeBO bo = new ChannelUniqueQrCodeBO();
            bo.setAvatar(entity.getAvatarUrl());
            bo.setFileKey(qrcodeFileName);
            bo.setLocalQrCode(sysFileVo.getUrl());
            String s = null;
            try {
                s = generateUniqueQrCode(bo);
            } catch (IOException e) {
                e.printStackTrace();
            }
            entity.setQrcodeUrl(s);
            entity.setWxConfigId(wxConfigId);
        }
      return channelCodeService.updateById(entity);
    }

    /**
     * 更新微信 配置客户联系「联系我」方式 二维码
     */
    @Async
    public void onUpdateWxAddContactWayQrcode(int codeId, Map<String, List<?>> map) {
        ChannelCodeEntity entity = channelCodeService.getById(codeId);
        if (entity == null) {
            throw new CheckedException("渠道码创建失败");
        }

        int corpId = entity.getCorpId();
        String wxConfigId = entity.getWxConfigId();

        boolean skipVerify = false;
        if (entity.getAutoAddFriendStatus().equals(1)){
            if (entity.getAutoAddFriendTimeStatus().equals(1)){
                skipVerify = true;
            }else {
                AutoAddFriendMsg msg = JSONObject.parseObject(entity.getAutoAddFriendMsg(), AutoAddFriendMsg.class);
                DateTime now = DateTime.now();
                long time = now.getTime();
                long startTime = DateUtil.parseDateTime(DateUtil.now().split(" ")[0] + " " + msg.getAutoAddFriendStartTime() + ":00").getTime();
                long endTime = DateUtil.parseDateTime(DateUtil.now().split(" ")[0] + " " + msg.getAutoAddFriendEndTime() + ":00").getTime();
                if (time >= startTime && time <= endTime){
                    skipVerify = true;
                }
            }
        }

        WxApiUtils.requestUpdateContactWay(corpId, wxConfigId, map.get("eIds"), map.get("dId"),skipVerify);
    }

    private String generateUniqueQrCode(ChannelUniqueQrCodeBO cuqcb) throws IOException {
        //获取联系我二维码
        File qrCodeFile = FilesUtil.getFileByURI(cuqcb.getLocalQrCode());
        BufferedImage qrCodeImage = ImageIO.read(qrCodeFile);

        //获取二维码头像
        File avatarFile = FilesUtil.getFileByURI(cuqcb.getAvatar());
        BufferedImage qrAvatarImage = ImageIO.read(avatarFile);

        //获取专属二维码背景
        BufferedImage image = new BufferedImage(396, 396,BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = image.createGraphics();

        //画笔属性设置
        g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        //绘制专属二维码
        //绘制背景
        Color c = g.getColor();
        g.setColor(new Color(245,245,245,255));
        g.fillRect(0,0, 396, 396);
        g.setColor(c);
        //绘制二维码
        g.drawImage(qrCodeImage,0,0,396, 396,null);
        //绘制二维码内头像
        g.drawImage(qrAvatarImage,158,158,80,80,null);

        //保存专属二维码
        String fileKey = StrUtil.isEmpty(cuqcb.getFileKey()) ? getUniqueQrCodeFileKey() : cuqcb.getFileKey();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image,"png", baos);
        ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
        SysFileVo vo = FilesUtil.uploadFile(bais, fileKey, true, true);
        log.info("生成专属二维码成功");

        String uniqueQrCode = vo.getUrl();
        return uniqueQrCode;
    }

    private String getUniqueQrCodeFileKey() {
        return Constant.UQC_DIR + FilesUtil.getRandomFileName("png");
    }

}
